import { Injectable, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Message } from './entities/message.entity';
import { CreateMessageDto } from './dto/create-message.dto';
import { UsersService } from '../users/users.service';
import { CozeApiService } from './coze-api.service';

@Injectable()
export class ChatService {
  constructor(
    @InjectRepository(Message)
    private messagesRepository: Repository<Message>,
    private usersService: UsersService,
    private cozeApiService: CozeApiService,
  ) {}

  async create(userId: number, createMessageDto: CreateMessageDto): Promise<Message> {
    const message = this.messagesRepository.create({
      content: createMessageDto.content,
      senderId: userId,
      receiverId: createMessageDto.receiverId,
      isAIMessage: createMessageDto.isAIMessage || false,
    });

    return this.messagesRepository.save(message);
  }

  async createAIMessage(userId: number, content: string): Promise<{ userMessage: Message; aiResponse: Message }> {
    // 创建用户发送的消息记录
    const userMessage = this.messagesRepository.create({
      content,
      senderId: userId,
      isAIMessage: true,
    });
    await this.messagesRepository.save(userMessage);
    
    try {
      // 调用Coze API获取AI回复
      const cozeResponse = await this.cozeApiService.sendMessage(
        userId.toString(),
        content,
        // 如果有现有对话，可以传入对话ID
      );
      
      // 从Coze API响应中提取AI回复内容
      const aiContent = cozeResponse.data?.messages?.[0]?.content || '抱歉，我暂时无法回复您的消息。';
      const conversationId = cozeResponse.data?.conversation_id;
      
      // 创建AI回复的消息记录
      const aiMessage = this.messagesRepository.create({
        content: aiContent,
        receiverId: userId,
        isAIMessage: true,
        metadata: { conversationId }, // 存储对话ID以便后续使用
      });
      const aiResponse = await this.messagesRepository.save(aiMessage);
      
      return { userMessage, aiResponse };
    } catch (error) {
      console.error('AI回复生成失败:', error);
      
      // 如果API调用失败，创建一个错误回复
      const errorMessage = this.messagesRepository.create({
        content: '抱歉，我暂时无法回复您的消息。请稍后再试。',
        receiverId: userId,
        isAIMessage: true,
      });
      const aiResponse = await this.messagesRepository.save(errorMessage);
      
      return { userMessage, aiResponse };
    }
  }

  async findAll(userId: number): Promise<Message[]> {
    return this.messagesRepository.find({
      where: [
        { senderId: userId },
        { receiverId: userId },
      ],
      order: { createdAt: 'DESC' },
      relations: ['sender', 'receiver'],
    });
  }

  async findConversation(userId: number, otherUserId: number): Promise<Message[]> {
    return this.messagesRepository.find({
      where: [
        { senderId: userId, receiverId: otherUserId },
        { senderId: otherUserId, receiverId: userId },
      ],
      order: { createdAt: 'ASC' },
    });
  }

  async findAIConversation(userId: number): Promise<Message[]> {
    return this.messagesRepository.find({
      where: [
        { senderId: userId, isAIMessage: true },
        { receiverId: userId, isAIMessage: true },
      ],
      order: { createdAt: 'ASC' },
    });
  }

  async markAsRead(messageId: number): Promise<Message> {
    const message = await this.messagesRepository.findOne({ where: { id: messageId } });
    if (!message) {
      throw new NotFoundException('消息不存在');
    }

    message.isRead = true;
    return this.messagesRepository.save(message);
  }

  async getUnreadCount(userId: number): Promise<number> {
    return this.messagesRepository.count({
      where: {
        receiverId: userId,
        isRead: false,
      },
    });
  }

  async getRecentChats(userId: number): Promise<any[]> {
    // 获取与用户相关的所有对话的最新消息
    const query = `
      SELECT 
        m.*,
        CASE 
          WHEN m.sender_id = ? THEN m.receiver_id
          ELSE m.sender_id
        END as chat_with_id
      FROM messages m
      INNER JOIN (
        SELECT 
          CASE 
            WHEN sender_id = ? THEN receiver_id
            ELSE sender_id
          END as other_user_id,
          MAX(created_at) as latest_time
        FROM messages
        WHERE sender_id = ? OR receiver_id = ?
        GROUP BY other_user_id
      ) latest ON (
        (m.sender_id = ? AND m.receiver_id = latest.other_user_id) OR
        (m.receiver_id = ? AND m.sender_id = latest.other_user_id)
      ) AND m.created_at = latest.latest_time
      ORDER BY m.created_at DESC
    `;

    const messages = await this.messagesRepository.query(query, [userId, userId, userId, userId, userId, userId]);
    
    // 获取未读消息数量
    const chats = [];
    for (const message of messages) {
      const otherUserId = message.chat_with_id;
      if (otherUserId) {
        const unreadCount = await this.messagesRepository.count({
          where: {
            senderId: otherUserId,
            receiverId: userId,
            isRead: false,
          },
        });

        let otherUser = null;
        try {
          otherUser = await this.usersService.findOne(otherUserId);
        } catch (error) {
          // 如果是AI消息，可能没有对应的用户
          if (message.is_ai_message) {
            otherUser = {
              id: 0,
              name: '智能助手',
              avatar: 'https://pic.rmb.bdstatic.com/bjh/cf932b001775db49a995d2ae7b32477e3627.png@h_1280',
            };
          }
        }

        if (otherUser) {
          chats.push({
            id: otherUserId,
            name: otherUser.name,
            avatar: { uri: `https://randomuser.me/api/portraits/${Math.random() > 0.5 ? 'women' : 'men'}/${Math.floor(Math.random() * 100)}.jpg` },
            lastMessage: message.content,
            time: this.formatMessageTime(new Date(message.created_at)),
            unread: unreadCount,
            isAI: message.is_ai_message,
          });
        }
      }
    }

    // 添加AI助手到聊天列表
    const hasAIChat = chats.some(chat => chat.isAI);
    if (!hasAIChat) {
      chats.unshift({
        id: 'ai-assistant',
        name: '智能助手',
        avatar: { uri: 'https://pic.rmb.bdstatic.com/bjh/cf932b001775db49a995d2ae7b32477e3627.png@h_1280' },
        lastMessage: '您好！我是您的AI助手，随时为您提供陪伴和帮助。有什么我可以为您做的吗？',
        time: '在线',
        unread: 0,
        isAI: true,
      });
    }

    return chats;
  }

  private formatMessageTime(date: Date): string {
    const now = new Date();
    const diff = now.getTime() - date.getTime();
    const dayDiff = Math.floor(diff / (1000 * 60 * 60 * 24));

    if (dayDiff === 0) {
      // 今天，显示时间
      return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
    } else if (dayDiff === 1) {
      // 昨天
      return '昨天';
    } else if (dayDiff < 7) {
      // 一周内，显示星期几
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return days[date.getDay()];
    } else {
      // 超过一周，显示日期
      return `${date.getMonth() + 1}月${date.getDate()}日`;
    }
  }
}